package org.example.day04;

/**
 * 第二章节:2.2.6:验证同步synchronized(this)代码块是锁定当前对象的
 */
public class MyThread6 {
    //添加了synchronized就同步了，线程A和B用了同一把锁，即m6对象
    synchronized public void otherMethod(){
        System.out.println("run ------------ otherMethod");
    }
    public void doLongTimeTask(){
        synchronized (this){
            for (int i = 0; i < 10000; i++) {
                System.out.println("ThreadName = " + Thread.currentThread().getName() + "   i = " + (i+1));
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread6 m6 = new MyThread6();
        Thread6A ta = new Thread6A(m6);
        ta.start();
        Thread.sleep(100); //确保A先拿到锁
        Thread6B tb = new Thread6B(m6);
        tb.start();
    }
}

class Thread6A extends Thread{
    private MyThread6 m6;

    public Thread6A(MyThread6 m6) {
        this.m6 = m6;
    }

    @Override
    public void run() {
        m6.doLongTimeTask();
    }
}

class Thread6B extends Thread{
    private MyThread6 m6;

    public Thread6B(MyThread6 m6) {
        this.m6 = m6;
    }

    @Override
    public void run() {
        m6.otherMethod();
    }
}
